/*
	This file is part of Android-CWG.

	Android-CWG is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Android-CWG is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Android-CWG.  If not, see <http://www.gnu.org/licenses/>.
*/

package cz.acwg.cwg;

import android.database.Cursor;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

class CatalogHandler extends DefaultHandler {
    private DatabaseAdapter db;
    private StringBuilder catalogTitle;
    private StringBuilder catalogId;
    private String cwgId;
    private StringBuilder jpg;
    private StringBuilder count;
    private StringBuilder version;
    private StringBuilder catalogType;
    private StringBuilder year;
    private StringBuilder comment;
    enum State {
        NONE, CWG, CAT_NO, NAME, IMAGE, PIECES, VERSION, CAT_TYPE, COMMENT, YEAR
    }
    private State state;

    public CatalogHandler(DatabaseAdapter db) {
        this.db = db;
        this.state = State.NONE;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        switch (this.state) {
            case CAT_NO:
                this.catalogId.append(ch, start, length);
                break;
            case NAME:
                this.catalogTitle.append(ch, start, length);
                break;
            case IMAGE:
                this.jpg.append(ch, start, length);
                break;
            case PIECES:
                if (this.count.length() == 0) {
                    this.count.append(ch, start, length);
                } else {
                    String sCount = this.count.toString().trim();
                    int iCount = Integer.parseInt(sCount) + 1;
                    this.count = new StringBuilder();
                    this.count.append(iCount);
                }
                break;
            case YEAR:
                if (this.year.length() == 0) {
                    this.year.append(ch, start, length);
                } else {
                    this.year.append(", ").append(ch, start, length);
                }
                break;
            case COMMENT:
                this.comment.append(ch, start, length);
                break;
            case VERSION:
                this.version.append(ch, start, length);
                break;
            case CAT_TYPE:
                this.catalogType.append(ch, start, length);
                break;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        int iCount = 0;
        int iYear = 0;
        String sJpg = "";
        switch (this.state) {
            case CWG:
                if (localName.equals("cwg")) {
                    this.state = State.NONE;

                    // Save to DB
                    String sCatalogId = this.catalogId.toString().trim();
                    String sCatalogTitle = this.catalogTitle.toString().trim();
                    String sCatalogType = this.catalogType.toString().trim();
                    String sVersion = this.version.toString().trim();
                    String sYear = this.year.toString().trim();
                    String sComment = this.comment.toString().trim();
                    String sJpgPath = this.jpg.toString().trim();
                    if (sJpgPath.lastIndexOf("/") >= 0) {
                        sJpg = sJpgPath.substring(sJpgPath.lastIndexOf("/") + 1);
                    };
                    String sCount = this.count.toString().trim();
                    if (sCount != "") {
                        iCount = Integer.parseInt(sCount);
                    }
                    long iId = Integer.parseInt(this.cwgId);
                    if (sCatalogId=="") sCatalogId = Long.toString(iId);
                    Cursor cur = db.getCwgByCatalogId(sCatalogId);
                    if (cur == null) {
                        db.addCwg(iId, sCatalogTitle, sCatalogTitle, sCatalogId, sCatalogType, sVersion, sYear, sComment, sJpg, iCount);
                    } else {
                        long id = cur.getLong(cur.getColumnIndex("_id"));
                        int count = cur.getInt(cur.getColumnIndex("count"));
                        String title = cur.getString(cur.getColumnIndex("title"));
                        db.updateCwgFromCatalog(id, title, sCatalogTitle, sCatalogId, sCatalogType, sVersion, sYear, sComment, sJpg, iCount);
                        cur.close();
                    }
                }
                break;
            case CAT_NO:
                if (localName.equals("cat_no")) {
                    this.state = State.CWG;
                }
                break;
            case NAME:
                if (localName.equals("name")) {
                    this.state = State.CWG;
                }
                break;
            case IMAGE:
                if (localName.equals("image")) {
                    this.state = State.CWG;
                }
                break;
            case PIECES:
                if (localName.equals("pieces")) {
                    this.state = State.CWG;
                }
                break;
            case COMMENT:
                if (localName.equals("comment")) {
                    this.state = State.CWG;
                }
                break;
            case VERSION:
                if (localName.equals("version")) {
                    this.state = State.CWG;
                }
                break;
            case YEAR:
                if (localName.equals("year")) {
                    this.state = State.CWG;
                }
                break;
            case CAT_TYPE:
                if (localName.equals("category")) {
                    this.state = State.CWG;
                }
                break;
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        switch (this.state) {
            case NONE:
                if (localName.equals("cwg")) {
                    this.state = State.CWG;
                    int idAtr = attributes.getIndex("id");
                    this.cwgId = attributes.getValue(idAtr);
                    this.catalogId = new StringBuilder();
                    this.catalogTitle = new StringBuilder();
                    this.jpg = new StringBuilder();
                    this.count = new StringBuilder();
                    this.version = new StringBuilder();
                    this.catalogType = new StringBuilder();
                    this.comment = new StringBuilder();
                    this.year = new StringBuilder();
                }
                break;
            case CWG:
                if (localName.equals("cat_no")) {
                    this.state = State.CAT_NO;
                } else if (localName.equals("name")) {
                    this.state = State.NAME;
                } else if (localName.equals("image")) {
                    this.state = State.IMAGE;
                } else if (localName.equals("pieces")) {
                    this.state = State.PIECES;
                } else if (localName.equals("category")) {
                    this.state = State.CAT_TYPE;
                } else if (localName.equals("version")) {
                    this.state = State.VERSION;
                } else if (localName.equals("comment")) {
                    this.state = State.COMMENT;
                } else if (localName.equals("year")) {
                    this.state = State.YEAR;
                }
                break;
        }
    }

}

class CatalogImport extends Import {
    private static final String TAG = "CwgCatalogImport";

    CatalogImport() {
    }

    void importData(DatabaseAdapter db) throws ImportException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            CatalogHandler handler = new CatalogHandler(db);
            parser.parse(this.getInput(), handler);
        } catch (ParserConfigurationException pce) {
            throw new ImportException(
                    pce.getClass().getName() + ": " + pce.getMessage(),
                    pce.getClass().getName() + ": " + pce.getLocalizedMessage(),
                    pce);
        } catch (SAXException saxe) {
            throw new ImportException(
                    saxe.getClass().getName() + ": " + saxe.getMessage(),
                    saxe.getClass().getName() + ": " + saxe.getLocalizedMessage(),
                    saxe);
        } catch (IOException ioe) {
            throw new ImportException(
                    ioe.getClass().getName() + ": " + ioe.getMessage(),
                    ioe.getClass().getName() + ": " + ioe.getLocalizedMessage(),
                    ioe);
        }
    }
}